package com.example.demo.controller;


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.awt.font.MultipleMaster;
import java.io.*;
import java.net.URLEncoder;
import java.net.http.HttpResponse;

@RestController
@RequestMapping("/file")
public class UpPicController {


    @RequestMapping("/updatePic")
    public String updatePic(MultipartFile file) throws IOException {
        long l = System.currentTimeMillis();
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String path="D:\\file\\pic\\";
        String createFile = path + l +fileType;
        File file1 = new File(createFile);
        file.transferTo(file1);

        return "http://localhost:8081/file/gtePic/"+l + fileType;
    }

    @RequestMapping("/gtePic/{name}")
    public void gtePic(@PathVariable("name") String name, HttpServletResponse response) throws IOException {

        String path="D:\\file\\pic\\";
        String createFile = path + name;
        File file = new File(createFile);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(buffer);
        outputStream.flush();
    }
}
